package cn.school.teacher.evaluation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.school.common.utils.SysUserUtils;
import cn.school.teacher.evaluation.dao.TeacherEvaluationDataDao;
import cn.school.teacher.evaluation.dao.TeacherEvaluationUserTaskDao;
import cn.school.teacher.evaluation.dto.TeacherEvaluationDataDto;
import cn.school.teacher.evaluation.dto.TeacherEvaluationUserTaskDto;
import cn.school.teacher.evaluation.entity.TeacherEvaluationData;
import cn.school.teacher.evaluation.entity.TeacherEvaluationTask;
import cn.school.teacher.evaluation.entity.TeacherEvaluationUserTask;
import cn.school.teacher.evaluation.service.EvaluationUserTaskService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 老师考核：考核主任务
 */
@Service
public class EvaluationUserTaskServiceImpl extends ServiceImpl<TeacherEvaluationUserTaskDao, TeacherEvaluationUserTask> implements EvaluationUserTaskService {
    @Resource
    private TeacherEvaluationDataDao teacherEvaluationDataDao;

    @Override
    public IPage<TeacherEvaluationUserTaskDto> getPage(Map<String, Object> params) {
        String userId = (String) params.get("loginUserId");
        String pageIndex = (String) params.get("pageNum");
        String pageSize = (String) params.get("pageSize");
        String beginTime = (String) params.get("beginTime");
        String endTime = (String) params.get("endTime");

        Page<TeacherEvaluationUserTaskDto> page = new Page<>();
        page.setSize(Integer.parseInt(pageSize));
        page.setCurrent(Integer.parseInt(pageIndex));

        QueryWrapper<TeacherEvaluationUserTaskDto> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(userId)) {
            queryWrapper.eq("teut.user_id", Long.parseLong(userId));
        }
        if (StrUtil.isNotEmpty(beginTime)) {
            queryWrapper.ge("teut.create_time", DateUtil.parse(beginTime + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
        }
        if (StrUtil.isNotEmpty(endTime)) {
            queryWrapper.le("teut.create_time", DateUtil.parse(endTime + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
        }
        //租户
        queryWrapper.eq("teut.tenant_id", SysUserUtils.getSysUser().getTenantId());
        queryWrapper.orderByDesc("teut.create_time");
        page = this.baseMapper.getPage(page, queryWrapper);
        return page;
    }

    @Override
    public TeacherEvaluationUserTaskDto getUserTaskItemData(Map<String, Object> params) {
        // 获取用户任务
        Page<TeacherEvaluationUserTaskDto> page = new Page<>();
        page.setCurrent(1);
        page.setSize(1);
        String teutId = (String) params.get("teutId");
        QueryWrapper<TeacherEvaluationUserTaskDto> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(teutId)) {
            queryWrapper.eq("teut.id", Long.parseLong(teutId));
        }
        TeacherEvaluationUserTaskDto teacherEvaluationUserTaskDto = null;
        page = this.baseMapper.getPage(page, queryWrapper);
        if (page.getRecords() != null && page.getRecords().size() != 0) {
            teacherEvaluationUserTaskDto = page.getRecords().get(0);
        }

        if (teacherEvaluationUserTaskDto!=null) {
            // 当用户任务是指定人员浏览时，更新为未开始 1
            Long loginUserId = (Long) params.get("loginUserId");
            if (loginUserId.longValue() == teacherEvaluationUserTaskDto.getUserId() && teacherEvaluationUserTaskDto.getTeutStatus()==0) {
                TeacherEvaluationUserTask tempUserTask = new TeacherEvaluationUserTask();
                BeanUtil.copyProperties(teacherEvaluationUserTaskDto, tempUserTask);
                tempUserTask.setId(teacherEvaluationUserTaskDto.getTeutId());
                tempUserTask.setTeutStatus((short)1); // 未开始
                this.baseMapper.updateById(tempUserTask);
            }
        }

        // 获取用户任务_打分数据
        if (teacherEvaluationUserTaskDto != null) {
            QueryWrapper<TeacherEvaluationDataDto> dataDtoQueryWrapper = new QueryWrapper<>();
            dataDtoQueryWrapper.eq("teut.id", teacherEvaluationUserTaskDto.getTeutId());
            dataDtoQueryWrapper.orderByAsc("teda.id");
            List<TeacherEvaluationDataDto> dataList = this.baseMapper.getTaskItemData(dataDtoQueryWrapper);
            dataList = this.processChirdenList(dataList);
            teacherEvaluationUserTaskDto.setItemDatelist(dataList);
        }
        return teacherEvaluationUserTaskDto;
    }

    @Override
    @Transactional
    public TeacherEvaluationUserTaskDto saveOrUpdateItemDate(Map<String, Object> params) {
        // 只保存存结叶子点的分数
        Long loginUserId = (Long) params.get("loginUserId");
        TeacherEvaluationUserTaskDto teacherEvaluationUserTaskDto = (TeacherEvaluationUserTaskDto) params.get("teacherEvaluationUserTaskDto");

        // 用户任务状态修改
        TeacherEvaluationUserTask userTask = this.baseMapper.selectById(teacherEvaluationUserTaskDto.getTeutId());
        if (userTask.getTeutStatus() == 3 || userTask.getTeutStatus() == 4) {
            return teacherEvaluationUserTaskDto;
        } else {
            if (teacherEvaluationUserTaskDto.getTeutStatus() == 4) {
                // 更新为已提交（正常结束）
                userTask.setTeutStatus(teacherEvaluationUserTaskDto.getTeutStatus());
            } else {
                // 更新为进行中
                userTask.setTeutStatus((short) 2);
            }
            this.baseMapper.updateById(userTask);
        }

        //
        List<TeacherEvaluationDataDto> listAllLeafNote = new ArrayList<>();
        if (teacherEvaluationUserTaskDto.getItemDatelist() != null) {
            TeacherEvaluationData teacherEvaluationData = null;

            for (TeacherEvaluationDataDto teacherEvaluationDataDto : teacherEvaluationUserTaskDto.getItemDatelist()) {
                listAllLeafNote.clear();
                if (teacherEvaluationDataDto.getChildren() == null || teacherEvaluationDataDto.getChildren().size() == 0) {
                    listAllLeafNote.add(teacherEvaluationDataDto);
                } else {
                    for (TeacherEvaluationDataDto child : teacherEvaluationDataDto.getChildren()) {
                        listAllLeafNote.add(child);
                    }
                }

                for (TeacherEvaluationDataDto evaluationDataDto : listAllLeafNote) {
                    teacherEvaluationData = new TeacherEvaluationData();
                    BeanUtil.copyProperties(evaluationDataDto, teacherEvaluationData);
                    teacherEvaluationData.setId(evaluationDataDto.getTedaId());
                    if (teacherEvaluationData.getId() == null) {
                        // 新增
                        teacherEvaluationData.setCreateTime(Calendar.getInstance().getTime());
                        teacherEvaluationData.setModifyTime(Calendar.getInstance().getTime());
                        this.teacherEvaluationDataDao.insert(teacherEvaluationData);
                        teacherEvaluationDataDto.setTedaId(teacherEvaluationData.getId());
                    } else {
                        // 更新
                        teacherEvaluationData.setModifyTime(Calendar.getInstance().getTime());
                        this.teacherEvaluationDataDao.updateById(teacherEvaluationData);
                    }
                }

            }
        }
        return teacherEvaluationUserTaskDto;
    }
    
    private List<TeacherEvaluationDataDto> processChirdenList(List<TeacherEvaluationDataDto> dataList) {
        List<TeacherEvaluationDataDto> list = new ArrayList<>();
        HashMap<Long, TeacherEvaluationDataDto> levelOneMap = new HashMap<>();

        TeacherEvaluationDataDto nodeVo = null;
        TeacherEvaluationDataDto nodeParentVo = null;
        for (int i = 0, size = dataList.size(); i < size; i++) {
            nodeVo = new TeacherEvaluationDataDto();
            BeanUtils.copyProperties(dataList.get(i), nodeVo);
            if (dataList.get(i).getTeitParentId() == null) {
                list.add(nodeVo);
                levelOneMap.put(nodeVo.getTeitId(), nodeVo);
            } else if (levelOneMap.containsKey(nodeVo.getTeitParentId())) {
                nodeParentVo = levelOneMap.get(nodeVo.getTeitParentId());
                if (nodeParentVo.getChildren() == null) {
                    List<TeacherEvaluationDataDto> childrenList = new ArrayList<>();
                    childrenList.add(nodeVo);
                    nodeParentVo.setChildren(childrenList);
                } else {
                    nodeParentVo.getChildren().add(nodeVo);
                }
            }
        }
        return list;
    }
    
    @Override
    public boolean isSuccessByTakeScore(TeacherEvaluationTask teacherEvaluationTask, Map<String, Object> computerMap) {
        // 统计总人数
        Integer sumMember = this.getSumMember(teacherEvaluationTask);
        // 统计已结束子任务个数。
        Integer socreSumMember = this.getSumMemberByHaveScore(teacherEvaluationTask);
        if (sumMember.intValue() == socreSumMember.intValue()) {
            // 统计总分
            Double sumScore = this.getSumScore(teacherEvaluationTask);
            computerMap.put("sumMember", sumMember);
            computerMap.put("sumScore", sumScore);
        }  else {
            return false;
        }
        return true;
    }
    
    @Override
    public Double getSumScore(TeacherEvaluationTask teacherEvaluationTask) {
        Double sumScore = this.baseMapper.getSumScore(teacherEvaluationTask.getId());
        return sumScore;
    }
    
    @Override
    public Integer getSumMember(TeacherEvaluationTask teacherEvaluationTask) {
        LambdaQueryWrapper<TeacherEvaluationUserTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeacherEvaluationUserTask::getTetaId, teacherEvaluationTask.getId());
        Integer count = this.baseMapper.selectCount(queryWrapper);
        return count;
    }
    
    @Override
    public Integer getSumMemberByHaveScore(TeacherEvaluationTask teacherEvaluationTask) {
        LambdaQueryWrapper<TeacherEvaluationUserTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeacherEvaluationUserTask::getTetaId, teacherEvaluationTask.getId());
        queryWrapper.eq(TeacherEvaluationUserTask::getTeutStatus, 4);
        Integer count = this.baseMapper.selectCount(queryWrapper);
        return count;
    }
    
    
}
